#coding:utf-8
from probe.core.level import *
from commands import *
import sys
def pings(args):
    '''监控服务器是否能ping通'''
    if not getcentermgrpid():
        sys.exit()
    losslist = {}
    iplist = endpoint_offline({})
    if not iplist:
        return WarningData({'conn mysql': [0, 'False']})
    for ipaddr in iplist:
        result = getoutput("ping -c 1 %s|grep loss|awk '{print $(NF-4)}'"%ipaddr).strip('%')
        try:
            if int(result) != 0:
                losslist[ipaddr]=[int(result),'%loss']
        except ValueError:
            losslist[ipaddr]=[result,'']
    if losslist:
        return WarningData(losslist)
    return InfoData(losslist)

def offline(args):
    '''监控Endpoint下线机器'''
    if not getcentermgrpid():
        sys.exit()
    offlist = {}
    iplist = endpoint_offline({})
    if not iplist:
        return WarningData({'conn mysql': [0, 'False']})
    for ipaddr in iplist:
        offlist[ipaddr]=['下线','<br />']
    if offlist:
        return WarningData(offlist)
    return InfoData(offlist)

def endpoint_offline(args):
    '''获取Endpoint下线机器'''
    hostname = 'localhost'
    user = 'ywuser'
    passwd = 'WG9jK46Nc5K5NZY4je0Z'
    result = getstatusoutput('mysql -h%s -u%s -p%s gsywdb -e "select iplist from t_os where isonline=0;"|grep -Ev "iplist|192.168" '%(hostname, user, passwd))
    if result[0] != 0:
        return False
    iplist = [ipaddr for i in result[1].split('\n') for ipaddr in i.split(',') if ipaddr.startswith('10.')]
    return iplist
def getcentermgrpid():
    '''获取Centermgr进程PID'''
    shell = '''ps x |grep centermgr |grep -E -v "daemon.sh|grep|startup.sh|centermgr.pid"| awk '{print $1}' '''
    centermgrpid = getoutput(shell)
    if not centermgrpid:
        return False
    return True

if __name__ == '__main__':
    print pings({})
